<?php
use GFPHP\Router, GFPHP\Cache, GFPHP\Loader, GFPHP\Hooks;

/**
 * 全局函数
 * 此处函数可在任何地方使用
 * 创建时间：2014-08-08 13:38 PGF
 * 修改时间：2016-02-15 10:25 PGF 添加
 */

/**
 * 根据行为获取网址
 * @param String
 * @param String
 * @return String
 */
function url($action = '', $get = '')
{
    return Router::$router->url($action, $get);
}

/**
 * @param $name
 * @param string $space
 * @return mixed
 */
function is_cache($name, $space = '')
{
    return Cache::is_cache($name, $space);
}

/**
 * @package Model
 * @param string
 * @uses Loader::model
 * @return Model\Model
 */
function model($mname = '')
{
    return Loader::model($mname);
}

/**
 * 引入Helper
 * @param string $helpername 函数库名称
 * @return bool
 */
function Helper($helpername)
{
    return Loader::Helper($helpername);
}

/**
 * 编译视图
 * @param $vname
 * @param bool $data
 * @param int $cacheTime
 * @param string $cacheKey
 * @return bool
 */
function view($vname, $data = FALSE, $cacheTime = 0, $cacheKey = '')
{
    return Loader::view($vname, $data, $cacheTime, $cacheKey);
}

/**
 * 钩子监听
 * @param $Hooks_name
 * @param array $params
 * @param string $type 类型
 * @return array|mixed|void
 */
function hooks($Hooks_name, $params, $type = 'call')
{
    switch ($type) {
        case 'call':
            return Hooks::call($Hooks_name, $params);
            break;
        case 'listen':
            Hooks::listen($Hooks_name, $params);
            break;
        case 'filter':
            return Hooks::filter($Hooks_name, $params);
    }

    return FALSE;
}

/**
 * 运行控制器指定方法
 * @param $cname
 * @param string $method
 * @param string $var
 * @return bool
 */
function controller($cname, $method = '', $var = '')
{
    return Loader::controller($cname, $method, $var);
}

/**
 * 加载第三方类库
 * @param $Vendor_name
 * @return Object
 */
function Vendor($Vendor_name)
{
    return Loader::Vendor($Vendor_name);
}

/**
 * 解析正确路径
 * @return string
 */
function parseDir()
{
    $dirs = func_get_args();
    $dir = '';
    foreach ($dirs as $d) {
        $d = trim($d);
        if (strlen($d) > 0) {
            if ($d[0] == '/')
                $d = substr($d, 1, strlen($d) - 1);
            if ($d[ strlen($d) - 1 ] != '/')
                $d .= '/';
            $dir .= $d;
        }
    }
    $dir = explode('/', $dir);
    $c = count($dir);
    for ($i = 0; $i < $c; $i++) {
        if ($dir[ $i ] == '')
            continue;
        if (strpos('..', $dir[ $i ]) !== FALSE) {
            if ($i > 0) {
                unset($dir[ $i - 1 ]);
                unset($dir[ $i ]);
            }
        }
    }

    return implode('/', $dir);
}

/**
 * 字符截取
 * @param $string
 * @param $length
 * @param string $dot
 * @return mixed|string
 */
function str_cut($string, $length, $dot = '...')
{
    $length = intval($length);
    $string = strip_tags($string);
    $strlen = mb_strlen($string, 'utf8');
    if ($strlen <= $length) return $string;
    $string = str_replace(array(' ', ' ', '&amp;', '"', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '<', '>', '&middot;', '&hellip;'), array('', '',
        '&', '"', "'", '&ldquo;', '&rdquo;', '&mdash;', '<', '>', '&middot;', '&hellip;'), $string);
    $string = preg_replace("/<\/?[^>]+>/i", '', $string);
    $strcut = mb_substr($string, 0, $length, 'utf-8');

    return $strcut . $dot;
}

/**
 * @param $path
 * @param int $mode
 * @return bool
 */
function mkpathdir($path, $mode = 0777)
{
    $dir = dirname($path);
    if (is_dir($dir))
        return TRUE;
    else
        return @mkdir($dir, $mode, TRUE);
}

/**
 * 获取ip地址
 */
function ip()
{

    if (isset($_SERVER)) {

        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {

            $IPaddress = $_SERVER["HTTP_X_FORWARDED_FOR"];

        } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {

            $IPaddress = $_SERVER["HTTP_CLIENT_IP"];

        } else {

            $IPaddress = $_SERVER["REMOTE_ADDR"];

        }

    } else {

        if (getenv("HTTP_X_FORWARDED_FOR")) {

            $IPaddress = getenv("HTTP_X_FORWARDED_FOR");

        } else if (getenv("HTTP_CLIENT_IP")) {

            $IPaddress = getenv("HTTP_CLIENT_IP");

        } else {

            $IPaddress = getenv("REMOTE_ADDR");

        }

    }

    return preg_match('/[\d\.]{7,15}/', $IPaddress, $matches) ? $matches [0] : '';
}

/**
 * 人性化的时间显示
 * @param  String $time Unix时间戳，默认为当前时间
 * @param  string $date_format 默认时间显示格式
 * @return String
 */
function toTime($time = NULL, $date_format = 'Y/m/d H:i:s')
{
    $time = is_null($time) ? time() : $time;
    $now = time();
    $diff = $now - $time;
    if ($diff < 10)
        return '刚刚 ';
    if ($diff < 60)
        return $diff . '秒前 ';
    if ($diff < (60 * 60))
        return floor($diff / 60) . '分钟前 ';
    if (date('Ymd', $time) == date('Ymd', $now))
        return '今天 ' . date('H:i:s', $time);

    return date($date_format, $time);
}

/**
 * 文件大小单位换算
 * @param  int $byte 文件Byte值
 * @return String
 */
function toSize($byte)
{
    if ($byte >= pow(2, 40)) {
        $return = round($byte / pow(1024, 4), 2);
        $suffix = "TB";
    } elseif ($byte >= pow(2, 30)) {
        $return = round($byte / pow(1024, 3), 2);
        $suffix = "GB";
    } elseif ($byte >= pow(2, 20)) {
        $return = round($byte / pow(1024, 2), 2);
        $suffix = "MB";
    } elseif ($byte >= pow(2, 10)) {
        $return = round($byte / pow(1024, 1), 2);
        $suffix = "KB";
    } else {
        $return = $byte;
        $suffix = "Byte";
    }

    return $return . " " . $suffix;
}

/**
 * xss过滤函数 --来自PHPCMS
 *
 * @param $string
 * @return string
 */
function remove_xss($string)
{
    $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $string);

    $parm1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');

    $parm2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');

    $parm = array_merge($parm1, $parm2);

    for ($i = 0; $i < sizeof($parm); $i++) {
        $pattern = '/';
        for ($j = 0; $j < strlen($parm[ $i ]); $j++) {
            if ($j > 0) {
                $pattern .= '(';
                $pattern .= '(&#[x|X]0([9][a][b]);?)?';
                $pattern .= '|(&#0([9][10][13]);?)?';
                $pattern .= ')?';
            }
            $pattern .= $parm[ $i ][ $j ];
        }
        $pattern .= '/i';
        $string = preg_replace($pattern, '', $string);
    }

    return $string;
}

/**
 * 网址跳转
 * @param $url
 * @param $time
 */
function redirect($url, $time = 0)
{
    if ($time > 0)
        header('Refresh:' . $time . ';url=' . $url);
    else {
        header('Location:' . $url);
        exit;
    }
}

/**
 * 将string转换成可以在正则中使用的正则
 * @param $str
 */
function srtToRE($str)
{
    $res = '';
    $regs = array(
        '.', '+', '-', '$', '[', ']', '{', '}', '(', ')', '\\', '^', '|', '?', '*', '/', '_',
    );
    $str = str_split($str, 1);
    foreach ($str as $s) {
        if (in_array($s, $regs))
            $res .= '\\' . $s;
        else
            $res .= $s;
    }

    return $res;
}

/**
 * 判断请求是否为ajax请求
 */
function isAjax()
{
    if (isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtoupper($_SERVER["HTTP_X_REQUESTED_WITH"]) == "XMLHTTPREQUEST")
        return TRUE;
    else
        return FALSE;
}

/**
 * 发送邮件
 * @param $address      邮件地址 如果为数组，则为多个
 * @param $Subject      邮件主题
 * @param $body         内容
 * @param $is_html      是否为HTML
 */
function send_mail($address, $Subject, $body, $is_html = FALSE, $replayaddress = FALSE)
{
    $Mailer = Loader::vendor('Mailer');
    $Mailer = $Mailer->init();
    if (is_array($address)) {
        foreach ($address as $adr) {
            $Mailer->addAddress($adr);
        }
    } else {
        $Mailer->addAddress($address);
    }
    $Mailer->isHTML($is_html);
    $Mailer->Subject = $Subject;
    $Mailer->Body = $body;
    if ($replayaddress)
        $Mailer->setFrom($replayaddress, '代发送');
    $ret = $Mailer->send();
    if (!$ret) {
        echo 'Mailer Error: ' . $Mailer->ErrorInfo;
    }

    return $ret;
}

/**
 * 系统路径转网址路径
 * @param $path
 * @return mixed
 */
function pathToUrl($path)
{
    $path = str_replace(__ROOT__, '/', $path);

    return str_replace(DIRECTORY_SEPARATOR, '/', $path);
}

/**
 * 产生随机字符串
 *
 * @param    int $length 输出长度
 * @param    string $chars 可选的 ，默认为 0123456789
 * @return   string     字符串
 */
function random($length, $chars = '0123456789')
{
    $hash = '';
    $max = strlen($chars) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $chars[ mt_rand(0, $max) ];
    }

    return $hash;
}

/**
 * 图片等比缩放，优先宽度
 * @param $imgUrl           图片地址
 * @param bool $width 宽度
 * @param bool $height 高度
 */
function thumb($imgUrl, $width = 'auto', $height = 'auto')
{

    if ($width == FALSE && $height == FALSE) {
        echo $imgUrl;

        return;
    } else {
        if ($width == 'auto' && $height == 'auto') {
            echo $imgUrl;

            return;
        }
        $img = Loader::vendor('image');
        $info = pathinfo($imgUrl);
        $dir = explode('/', $info['dirname']);
        $dir = $dir[3];
        $picPath = __ROOT__ . 'runtime/thumb/' . $dir . '/' . $info['filename'] . '/' . $width . 'X' . $height . '.png';
        $urlpath = '/runtime/thumb/' . $dir . '/' . $info['filename'] . '/' . $width . 'X' . $height . '.png';
        $info = pathinfo($picPath);
        if (!is_dir($info['dirname'])) {
            mkdir($info['dirname'], 0777, 1);
        }
        if (file_exists($picPath)) {
            echo $urlpath;

            return;
        }
        if (preg_match('/^http:\/\//i', $imgUrl))
            $image = $img->CreateThumbnail($imgUrl, $width == 'auto' ? FALSE : $width, $height == 'auto' ? FALSE : $height, $picPath);
        else
            $image = $img->CreateThumbnail(__ROOT__ . $imgUrl, $width == 'auto' ? FALSE : $width, $height == 'auto' ? FALSE : $height, $picPath);
        echo $urlpath;
    }
}
